package com.youlai.system.plugin.easyexcel;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.youlai.system.model.entity.*;
import com.youlai.system.model.vo.AccountSourceImportVO;
import com.youlai.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Arrays;

/**
 * 账号人员批次导入监听器
 */
@Slf4j
public class AccountSourceImportListener extends MyAnalysisEventListener<AccountSourceImportVO> {

    private final SysSourceService sourceService;


    private final SysUserService userService;

    private final SysUserRoleService userRoleService;

    private final PasswordEncoder passwordEncoder;

    private final SysRoleService roleService;

    private final SysDeptService deptService;

    private final SysPositionService positionService;

    private final SysGradeService gradeService;

    private final Long deptId;

    public AccountSourceImportListener(Long deptId) {
        this.deptId = deptId;
        this.sourceService = SpringUtil.getBean(SysSourceService.class);
        this.userService = SpringUtil.getBean(SysUserService.class);
        this.passwordEncoder = SpringUtil.getBean(PasswordEncoder.class);
        this.userRoleService = SpringUtil.getBean(SysUserRoleService.class);
        this.roleService = SpringUtil.getBean(SysRoleService.class);
        this.deptService = SpringUtil.getBean(SysDeptService.class);
        this.positionService = SpringUtil.getBean(SysPositionService.class);
        this.gradeService = SpringUtil.getBean(SysGradeService.class);
    }

    @Override
    public String getMsg() {
        // 总结信息
        String summaryMsg = StrUtil.format("导入账号人员批次记录结束：成功{}条，失败{}条；<br/>{}", validCount, invalidCount, msg);
        return summaryMsg;
    }

    @Override
    public void invoke(AccountSourceImportVO accountSourceImportVO, AnalysisContext analysisContext) {
        log.info("解析到一条账号人员批次记录数据:{}", JSONUtil.toJsonStr(accountSourceImportVO));
        // 校验数据
        StringBuilder validationMsg = new StringBuilder();
        if (StrUtil.isBlank(accountSourceImportVO.getAccount())) {
            validationMsg.append("工号为空");
        }

        //工号校正
        if (StrUtil.isNotBlank(accountSourceImportVO.getAccount()) && accountSourceImportVO.getAccount().length() == 7) {
            accountSourceImportVO.setAccount("0" + accountSourceImportVO.getAccount());
        }

        if (StrUtil.isNotBlank(accountSourceImportVO.getAccount()) && accountSourceImportVO.getAccount().length() != 8) {
            validationMsg.append("工号长度应该为8位，请注意这个工号是否正确: "+ accountSourceImportVO.getAccount());
        }

        if (StrUtil.isBlank(accountSourceImportVO.getUsername())) {
            validationMsg.append("姓名为空");
        }

        //默认为学生角色
        SysRole role = roleService.getStudentRole();
        if (role == null) {
            validationMsg.append("没有找到指定的培训司机角色，请先到角色管理添加code为[STUDENT]的培训司机角色");
        }

        if (validationMsg.isEmpty()) {

            //账号处理
            Long sourceId = null;
            Long positionId = null;
            Long gradeId = null;
            //人员批次处理
            if (StrUtil.isNotBlank(accountSourceImportVO.getSource())) {
                SysSource source = sourceService.getByContentEqual(accountSourceImportVO.getSource());
                if (source == null) {
                    sourceId = sourceService.saveByContent(accountSourceImportVO.getSource());
                } else {
                    sourceId = source.getId();
                }
            }

            //岗位处理
            if (StrUtil.isNotBlank(accountSourceImportVO.getPosition())) {
                SysPosition position = positionService.getByContentEqual(accountSourceImportVO.getPosition());
                if (position == null) {
                    positionId = positionService.saveByContent(accountSourceImportVO.getPosition());
                } else {
                    positionId = position.getId();
                }
            }

            //职级处理
            if (StrUtil.isNotBlank(accountSourceImportVO.getGrade())) {
                SysGrade grade = gradeService.getByContentEqual(accountSourceImportVO.getGrade());
                if (grade == null) {
                    gradeId = gradeService.saveByContent(accountSourceImportVO.getGrade());
                } else {
                    gradeId = grade.getId();
                }
            }

            //根据账号（账号具有唯一性）、姓名、人员批次更新或者新增用户
            SysUser user = userService.getByAccount(accountSourceImportVO.getAccount());
            if (user == null) {
                user = userService.saveStudent(accountSourceImportVO.getAccount(), accountSourceImportVO.getUsername(), sourceId, positionId, gradeId);
            } else {
                user.setNickname(accountSourceImportVO.getUsername());
                user.setSourceId(sourceId);
                user.setPositionId(positionId);
                user.setGradeId(gradeId);
            }


            if (!userRoleService.hasAssignedRole(user.getId(), role.getId())) {
                userRoleService.saveUserRoles(user.getId(), Arrays.asList(role.getId()));
            }
            //默认为顶级部门
            SysDept dept = deptService.getById(this.deptId);

            if (dept != null && user.getDeptId() == null) {
                user.setDeptId(dept.getId());
            }

            userService.updateById(user);

            validCount++;
        } else {
            invalidCount++;
            msg.append("第" + (validCount + invalidCount) + "行数据校验失败：").append(JSONUtil.toJsonStr(accountSourceImportVO)).append(validationMsg + "<br/>");
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
